<template>

  <!-- 添加用户和批量删除 -->
  <el-card style="margin: 10px 0">
    <el-tooltip content="添加" placement="top">
      <el-button
          type="success"
          size="default"
          icon="Plus"
          @click="handleAdd"
      >
      </el-button>
    </el-tooltip>
    <!-- table展示用户信息 -->
    <el-table
        style="margin: 10px 0"
        border
        :data="bannerTableData"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column
          label="名称"
          align="center"
          prop="altname"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="课程id"
          align="center"
          prop="coursesId"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="图片"
          align="center"
          prop="imgurl"
          show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-image style="width: 100px; height: 100px;" :preview-src-list="[row.imgurl]" :src="row.imgurl"
                    fit="cover"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150px" align="center">
        <template #="{ row }">
          <el-tooltip content="编辑" placement="top">
            <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="handleEdit(row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-popconfirm
                :title="`你确定要删除吗?`"
                width="260px"
                @confirm="handleDelete(row.id)"
            >

              <template #reference>
                  <el-button
                      type="danger"
                      size="small"
                      icon="Delete"
                  >
                  </el-button>
              </template>
            </el-popconfirm>
          </el-tooltip>
        </template>

      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="findAll"
        @size-change="handler"
    />
  </el-card>

  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{ bannerForm.id ? '更新' : '添加' }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="bannerForm" :rules="rules" ref="formRef">
        <el-form-item label="图片名称" prop="altname">
          <el-input
              placeholder="请您输入图片名称"
              v-model="bannerForm.altname"
          ></el-input>
        </el-form-item>
        <el-form-item label="课程id" prop="coursesId">
          <el-input
              placeholder="请您输入课程id"
              v-model="bannerForm.coursesId"
              type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="imgurl">
          <el-upload
              class="upload-demo"
              :show-file-list="false"
              accept=".png,.jpg,.jpeg,.gif"
              drag
              :before-upload="handleBeforeUpload"
              :http-request="handleCustomUploadReport"
              multiple
          >
            <img style="max-width: 100%; height: auto;" v-if="bannerForm.imgurl"
                 :src="bannerForm.imgurl" class="avatar" alt="图片"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>


</template>

<script setup lang="ts">
import {ref, reactive, onMounted, nextTick} from 'vue'
import {ElFormItem, ElMessage} from 'element-plus'
import {Plus} from "@element-plus/icons-vue";
import {apiGet, apiPost} from "@/utils/api.ts";
// 表单数据
let bannerForm = reactive({id: 0, altname: '', imgurl: '', coursesId: 0,})
//默认页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(5)
//总个数
let total = ref<number>(0)
//存储全部用户的数组
let bannerTableData = ref([])
//定义响应式数据控制抽屉的显示与隐藏 添加用户和修改用户
let drawer = ref<boolean>(false)
//获取form组件实例
let formRef = ref<any>()


//获取全部用户信息
let findAll = async (pager = 1) => {
  //收集当前页码
  pageNo.value = pager
  let parameter = {
    page: pageNo.value,
    limit: pageSize.value,
  }
  //获取表单数据
  let {data} = await apiGet('/banner/findAll', parameter)
  total.value = data.count
  bannerTableData.value = data.data
}

//分页器下拉菜单的自定义事件的回调
const handler = () => {
  findAll()
}

//添加用户按钮的回调
const handleAdd = () => {
  //抽屉显示出来
  drawer.value = true
  //清空userParams的数据以及userParams继承User里面的所有数据
  Object.assign(bannerForm, {
    id: 0,
    altname: '',
    imgurl: '',
    coursesId: 0,
  })
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

//更新用户按钮的回调
const handleEdit = (row: any) => {
  //抽屉显示出来
  drawer.value = true
  //将用户的信息赋值给userParams
  Object.assign(bannerForm, {
    id: row.id,
    altname: row.altname,
    imgurl: row.imgurl,
    coursesId: row.coursesId,
  })
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

//保存按钮的回调
const save = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate()
  //保存按钮:添加新的用户|更新已有的用户账号信息
  bannerForm.id ? await apiPost('/banner/edit', {...bannerForm}) : await apiPost('/banner/add', {...bannerForm})
  await findAll()
  drawer.value = false
}

//删除
const handleDelete = async (id: number) => {
  await apiPost('/banner/delete', {id})
  await findAll(bannerTableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
}


//校验回调函数
const validatorAltname = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 1) {
    callBack()
  } else {
    callBack(new Error('图片名称至少1位'))
  }
}
//校验回调函数
const validatorImgurl = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 1) {
    callBack()
  } else {
    callBack(new Error('请上传图片，不能为空'))
  }
}
const validatorCoursesId = (rule: any, value: any, callBack: any) => {
  if (value >= 1) {
    callBack()
  } else {
    callBack(new Error('请输入课程id，不能为空不能为0'))
  }
}

//表单校验的规则对象
const rules = {
  altname: [{required: true, trigger: 'blur', validator: validatorAltname}],
  imgurl: [{required: true, trigger: 'blur', validator: validatorImgurl}],
  coursesId: [{required: true, trigger: 'blur', validator: validatorCoursesId}],
}

//上传文件之前做的一些判断
const handleBeforeUpload = (file) => {
  // 检查文件类型 只能上传.png,.jpg,.jpeg,.gif
  const isExcel = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif';
  if (!isExcel) {
    ElMessage.error('上传文件只能是.png,.jpg,.jpeg,.gif 格式!');
    return false;
  }

  //上传文件大小不能超过20M
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    ElMessage.error('上传文件大小不能超过 20MB!');
    return false;
  }
  return isExcel && isLt20M;
};
//导入资格证书文件事件
const handleCustomUploadReport = async (option) => {
  const formData = new FormData();
  formData.append('file', option.file);
  let {msg} = await apiPost('/upload/img', formData, {headers: {'Content-Type': 'multipart/form-data'}});
  bannerForm.imgurl = msg;
};

//组件挂载完毕
onMounted(() => {
  findAll()
})
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
